from selenium import webdriver

class TestDemo(object):

    def __init__(self,url,brower_type):
        self.driver = self.open_brower(brower_type)
        self.visit(url)

    #访问url
    def visit(self,url):
        self.driver.get(url)

    #关闭浏览器释放资源
    def close_brower(self):
        self.driver.quit()

    #打开浏览器
    def open_brower(self,brower_type):
        if brower_type == "chrome":
            chrome_options = webdriver.ChromeOptions()
            #自动化脚本在调用浏览器驱动的时候，如果不想每执行一次就打开一次浏览器 可以引用无头模式
            #chrome_options.add_argument('headless')
            #去掉chrome正受到自动测试软件的控制的提示
            chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
            driver = webdriver.Chrome(options=chrome_options)
            return driver
        elif brower_type == "firefox":
            driver = webdriver.Firefox()
            return driver
        else:
            print("brower_type error")

    #元素定位
    def locator(self,locator_type,value):
        if locator_type == 'xpath':
            el = self.driver.find_element_by_xpath(value)
            return el
        elif locator_type == 'id':
            el = self.driver.find_element_by_id(value)
            return el
        elif locator_type == 'css_selector':
            el = self.driver.find_element_by_css_selector(value)
            return el
        else:
            el = self.driver.find_element_by_name(value)
            return el
    #输入
    def input_text(self,locator_type,value,text):
        self.locator(locator_type,value).send_keys(text)

    #点击
    def click_element(self,locator_type,value):
         self.locator(locator_type,value).click()

#运行主函数
if __name__ =='__main__':
        tk= TestDemo("http://www.baidu.com","chrome")
        tk.input_text("id","kw","虚竹")
        tk.click_element("id","su")